<template>
  <div>
    <!--路径导航-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/users' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>活动管理</el-breadcrumb-item>
      <el-breadcrumb-item>活动列表</el-breadcrumb-item>
      <el-breadcrumb-item>活动详情</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card" :body-style="{ padding:'10px'}">
      <!--提示栏 -->
      <el-alert title="添加商品信息" type="info" show-icon center finish-status="success"></el-alert>
      <!--步骤栏 :active="activeNode-0"表示当前的步骤位置 -->
      <el-steps :active="activeNode-0" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 添加商品表单 -->
      <el-form
        :model="addGoodsForm"
        :rules="rules"
        ref="addGoodsForm"
        label-width="100px"
        label-position="top"
      >
      <!--标签导航-->
        <el-tabs
          tab-position="left"
          style="height: 100%;"
          :stretch="true"
          v-model="activeNode"
          :before-leave="beforeLeave"
          @tab-click="tabClick"
        >
          <!-- 基本信息标签栏 -->
          <el-tab-pane label="基本信息">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addGoodsForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addGoodsForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addGoodsForm.goods_number"></el-input>
            </el-form-item>
            <!-- 获取商品分类 多级选择器 el-cascader-->
            <el-form-item label="商品分类">
              <el-cascader
                :options="cateList"
                :props="cateProps"
                clearable
                style="width:400px;"
                v-model="addGoodsForm.goods_cat"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品参数标签栏 -->
          <el-tab-pane label="商品参数">
            <el-form-item :label="item.attr_name" v-for="(item) in manyTab" :key="item.attr_id">
              <!-- 循环复选框 -->
              <el-checkbox-group v-model="checkList">
                <el-checkbox :label="itemLab" v-for="(itemLab,i) in item.attr_vals" :key="i" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品属性标签栏 -->
          <el-tab-pane label="商品属性">
            <el-form-item :label="item.attr_name" v-for="(item) in onlyTab" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品图片标签栏 -->
          <el-tab-pane label="商品图片">
            <!-- 使用upload 上传图片文件  需要手动修改上传地址action="http://127.0.0.1:8888/api/private/v1/upload" -->
            <!-- 还要手动修改请求头 :headers="header" 请求头要带上token值 -->
            <el-upload
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :on-success="handleSuccess"
              :headers="header"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <!-- 商品内容标签栏 -->
          <el-tab-pane label="商品内容">
            <!-- npm i vue-quill-editor 富文本编辑器 -->
            <quill-editor  v-model="addGoodsForm.goods_introduce"></quill-editor>
            <el-button type='primary' @click='addGoods'>添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <!-- 图片预览弹窗 -->
      <el-dialog title="预览图片" :visible.sync="dialogVisible" width="30%">
        <img :src="imgPath" alt="上传图片失败" />
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
import _ from 'lodash'
export default {  
  created() {
    this.getCateList();
  },
  data() {
    return {
      //当前标签导航和步骤位置
      activeNode: "0",
      //商品表格
      addGoodsForm: {
        goods_name: "",
        goods_price: "",
        goods_number: "",
        goods_weight: "",
        goods_introduce: "",
        goods_cat: [],
        pic: [],
        attrs:[]
      },
      // 表格检验规则
      rules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" }
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" }
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" }
        ],
        goods_introduce: [
          { required: true, message: "请选择商品分类", trigger: "blur" }
        ]
      },
      //获取商品分类
      cateList: [],
      cateProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        expandTrigger: "hover"
      },
      // 动态属性和静态参数
      manyTab: [],
      onlyTab: [],
      checkList: [],
      // 修改图片上传的请求头 Authorization
      header: {
        Authorization: window.sessionStorage.getItem("token")
      },
      // 图片地址
      imgPath: "",
      dialogVisible: false
    };
  },
  methods: {
    // 获取商品数据
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status != 200) return this.$message.error("获取数据失败");
      this.cateList = res.data;
    },
    //标签导航切换时触发函数  return false 表示禁止切换
    beforeLeave(activename, oldname) {
      if (oldname == 0 && this.addGoodsForm.goods_cat.length != 3) return false;
    },
    //标签栏改变时 触发函数
    async tabClick() {
      if (this.activeNode == 1) {
        // 获取动态参数
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: "many" }
          }
        );
        if (res.meta.status != 200) return this.$message.error("获取数据失败");
        res.data.forEach(item => {
          item.attr_vals =
            item.attr_vals.length == 0 ? [] : item.attr_vals.split(",");
        });
        this.manyTab = res.data;
      } else if (this.activeNode == 2) {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: "only" }
          }
        );
        if (res.meta.status != 200) return this.$message.error("获取数据失败");
        this.onlyTab = res.data;
      }
    },
    // 图片预览
    handlePreview(file) {
      // console.log(file);
      this.imgPath = file.response.data.url;
      this.dialogVisible = true;
    },
    //图片移除
    handleRemove(file) {
      // console.log(file)
      var removeImgPath = file.response.tem_path;
      var removeImg = this.addGoodsForm.pic.indexOf(
        x => x.tem_path == removeImgPath
      );
      this.addGoodsForm.pic.splice(removeImg, 1);
      // console.log(this.addGoodsForm)
    },
    // 上传成功
    handleSuccess(response) {
      // console.log(response);
      const picInfo = { pic: response.data.tmp_path };
      this.addGoodsForm.pic.push(picInfo);
      // console.log(this.addGoodsForm)
    },
    // 提交添加商品表格
    addGoods(){
      this.$refs.addGoodsForm.validate(async valid=>{
        if(!valid) return this.$message.error('请完整填写信息')
        // 深度克隆数据 lodash 
        const newForm=_.cloneDeep(this.addGoodsForm)
        newForm.goods_cat=newForm.goods_cat.join(',')
        // 处理attrs
        this.onlyTab.forEach(item=>{
           const newAttrs={
             attr_id:item.attr_id,
             attr_value:item.attr_vals
           }
           this.addGoodsForm.attrs.push(newAttrs)
        })
        this.manyTab.forEach(item=>{
           const newAttrs={
             attr_id:item.attr_id,
             attr_value:item.attr_vals.join(' ')
           }
           this.addGoodsForm.attrs.push(newAttrs)
        })
        newForm.attrs=this.addGoodsForm.attrs
        const {data:res}=await this.$http.post('goods',newForm)
        if(res.meta.status!=201) return this.$message.error('添加商品失败')
        this.$message.success('添加商品成功')
        this.activename=5
        this.$router.push('/goods')
      })
    }
  },
  computed: {
    cateId() {
      return this.addGoodsForm.goods_cat.length == 3
        ? this.addGoodsForm.goods_cat[2]
        : "";
    }
  }
};
</script>
<style lang="less">
.el-steps {
  margin: 10px 5px;
}
</style>